// pages/main/index/postDetail/fyz_Select_Job/fyz_Select_Job.js
const app = getApp()
const globalData = getApp().globalData;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    fromUrl: '',
    showLoading: true,
    activeIndex: 0,
    showSearch: false,
    listTopHeight: 0,
    listTopInitHeight: 0,
    searchVal: '',
    searchResult: [],
    leftDomsTop: [],
    rightDomsTop: [],
    rightScrollTop: 0,
    leftScrolllTop: 0,
    cateItemHeight: 0,
    jobList: [],
    jobDetails: [],
    selectItems: [],
    selectName: [],

    //其他数据
    resumeJobId: [], //简历 意愿工作岗位ID
    resumeJobName: [],  //简历 意愿工作岗位name
    resumeUsedJobId: [],  //简历 曾经工作岗位ID
    resumeUsedJobName: [],  //简历 曾经工作岗位名称
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    const passMap = JSON.parse(options.param)
    this.data.fromUrl = passMap.from;
    console.log(passMap)
    console.log(this.data.fromUrl)
    if (this.data.fromUrl == 'setJob') {
      wx.setNavigationBarTitle({
        title: '期望工作岗位',
      });
    } else if (this.data.fromUrl == 'useDJob') {
      wx.setNavigationBarTitle({
        title: '曾经做过',
      });
    }
    //页面刷新一次，防止乱界面
    this.setData({
    })

    //获取顶部高度
    wx.nextTick(()=>{
      const query = wx.createSelectorQuery().in(this)
      query.select('.search-box').boundingClientRect(data => {
        that.data.listTopHeight = data.height
        that.data.listTopInitHeight = data.height + 1
        // console.log(that.listTopHeight)
        // console.log('获取顶部高度')
        that.setData({
          listTopHeight: that.data.listTopHeight,
          listTopInitHeight: that.data.listTopInitHeight
        })
      }).exec();
    })

    //获取工作岗位 接口
    this.getPositions()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //全局数据获取
    this.data.resumeJobId = globalData.resumeJobId
    this.data.resumeJobName = globalData.resumeJobName
    this.data.resumeUsedJobId = globalData.resumeUsedJobId
    this.data.resumeUsedJobName = globalData.resumeUsedJobName

    if (this.data.fromUrl == 'setJob') {
      this.data.selectItems = this.data.resumeJobId
      this.data.selectName = this.data.resumeJobName

    } else if (this.data.fromUrl == 'useDJob') {
      this.data.selectItems = this.data.resumeUsedJobId
      this.data.selectName = this.data.resumeUsedJobName

    }

    //页面刷新
    this.setData({
      selectItems: this.data.selectItems,
      selectName: this.data.selectName,
    })
  },

  //获取工作岗位
  getPositions(){
    let that = this
    wx.showLoading({
      title: '加载中，请稍等~',
    });
    app.$http.getPositionsForRecruit().then(res => {
      wx.hideLoading();
      // console.log(JSON.stringify(res))

      for (const val in res) {
        that.data.jobList.push(val)
        that.data.jobDetails.push(res[val])
      }

      // console.log(that.data.jobList)
      // console.log(that.data.jobDetails)
      
      //页面刷新
      that.setData({
        jobList: that.data.jobList,
        jobDetails: that.data.jobDetails,
      })

      //获取DOM节点信息
      that.getDomInfo()
    })
  },

  //获取左列表和右列表节点信息
  getDomInfo(){
    let that = this
    setTimeout(() => {
      wx.nextTick(() => {
        //获取左列表dom
        that.getElInfo({
          all: 'left',
          size: true,
          rect: true
        }).then(data => {
          that.data.leftDomsTop = data.map(v => {
            that.data.cateItemHeight = v.height
            return v.top
          })
          // console.log(that.data.leftDomsTop)
        })
        //获取右列表dom
        that.getElInfo({
          all: 'right',
          size: false,
          rect: true
        }).then(data => {
          that.data.rightDomsTop = data.map(v => {
            return v.top
          })
          // console.log(that.data.rightDomsTop)
        })
      })
    }, 500);

  },
  //获取节点信息
  getElInfo(obj = {}){
    return new Promise((res,rej) => {
      let option = {
        size: obj.size ? true : false,
        rect: obj.rect ? true : false,
        scrollOffset: obj.scrollOffset ? true : false,
      }
      const query = wx.createSelectorQuery().in(this);
      let tempQuery = obj.all ? query.selectAll(`.${obj.all}-scroll-item`) : query.select('#leftScroll')
      tempQuery.fields(option, data => {
        res(data)
      }).exec()
    })

  },

  //搜索框内容变化
  searchJob(e){
    // let dataset = e.currentTarget.dataset;

    let value = e.detail.value
    if (!value) {
      return
    }
    // console.log(value.length)
    // console.log(value)
    var tempStr =value.trim()
    // console.log('去除空格后')
    // console.log(tempStr.length)
    this.data.searchVal = tempStr
    if(this.data.searchVal && this.data.searchVal.length > 0){
      this.data.showSearch = true
    } else {
      this.data.showSearch = false
    }
    let result = []
    let key = this.data.searchVal
    if (!key || !key.length) {
      this.data.searchResult =[]
      //页面刷新
      this.setData({
        searchVal: this.data.searchVal,
        showSearch: this.data.showSearch,
        searchResult: this.data.searchResult
      })
      return
    }
    this.data.jobDetails.forEach((list,index) => {
      list.forEach(item => {
        if (item.name.includes(key)) {
          item.fname = this.data.jobList[index]
          result.push(item)
        }
      })
    })

    this.data.searchResult = result

    //页面刷新
    this.setData({
      searchVal: this.data.searchVal,
      showSearch: this.data.showSearch,
      searchResult: this.data.searchResult
    })

  },

  //关闭搜索
  closeSearch(){
    this.data.searchVal = '';
    this.data.showSearch = false
    this.searchResult = [];
    //刷新页面
    this.setData({
      searchVal: this.data.searchVal,
      showSearch: this.data.showSearch,
      searchResult: this.searchResult
    })
  },

  //顶部已选择item 点击
  cancleItem(e){
    // console.log(e)
    let that  = this
    const {id,name} = e.currentTarget.dataset;
    // console.log(`${id}`+" "+`${name}`)
    this.removeArr(this.data.selectName,name)
    this.removeArr(this.data.selectItems,id)

    //页面刷新
    this.setData({
      selectName: this.data.selectName,
      selectItems: this.data.selectItems
    })

    wx.nextTick(()=>{
      const query = wx.createSelectorQuery().in(this);
      query.select('.search-box').boundingClientRect(data => {
        that.data.listTopHeight = data.height
        //页面刷新
        that.setData({
          listTopHeight: that.data.listTopHeight
        })
      }).exec();
    })
  },
  removeArr(arr,val){
    var index = arr.indexOf(val)
    if (index > -1) {
      arr.splice(index,1)
    }
    return arr
  },

  //点击右侧列表item
  changeId(e){
    // console.log(e)
    const {item} = e.currentTarget.dataset
    let that = this
    let id = item.id
    let name = item.name
    this.data.searchVal = ''
    this.data.searchResult = []
    this.data.showSearch = false
    if (this.data.selectItems.length >= 10 && !this.data.selectItems.includes(id)) {
      wx.showToast({title: '最多十项',})
      return
    }
    if(this.data.selectItems.includes(id)) {
      this.removeArr(this.data.selectItems, id)
      this.removeArr(this.data.selectName, name)
    }else{
      this.data.selectItems.push(id);
      this.data.selectName.push(name)
    }

    //刷新页面
    that.setData({
      searchVal: that.data.searchVal,
      searchResult: that.data.searchResult,
      showSearch: that.data.showSearch,
      selectItems: that.data.selectItems,
      selectName: that.data.selectName,
    })

    // wx.nextTick(() =>{
      const query = wx.createSelectorQuery().in(this);
      query.select('.search-box').boundingClientRect(data => {
        this.data.listTopHeight = data.height
        //刷新页面
        that.setData({
          listTopHeight: that.data.listTopHeight
        })
      }).exec();
    // })
    // console.log(that.data.selectItems)
  },

  //左列表点击
  changeCate(e){
    // console.log(e)
    const {index} = e.currentTarget.dataset
    this.data.activeIndex = index
    this.data.rightScrollTop = (this.data.rightDomsTop[index] - this.data.listTopInitHeight)
    // console.log(this.data.rightScrollTop)
    //刷新页面
    this.setData({
      activeIndex: this.data.activeIndex,
      rightScrollTop: this.data.rightScrollTop
    })
  },
  //右侧列表滚动监听
  async onRightScroll(e){
    let scrollHeight = e.detail.scrollTop
    let compareHeight = scrollHeight + this.data.listTopInitHeight + 20
    //+20防止最底部的不高亮
    // 匹配当前scrollTop所处的索引
    this.data.rightDomsTop.forEach((value,key)=>{
      if (value < compareHeight) {
        this.data.activeIndex = key
      }
    })
    //刷新页面
    this.setData({
      activeIndex: this.data.activeIndex
    })
  },


  //底部的点击提交按钮
  commit(){
    //全局数据获取
    if(this.data.fromUrl === 'setJob'){
      // console.log('期望工作岗位全局保存')
      globalData.resumeJobId=this.data.selectItems
      globalData.resumeJobName=this.data.selectName
    }else if(this.data.fromUrl === 'useDJob'){
      // console.log('曾经做过的职位全局保存')
      globalData.resumeUsedJobId=this.data.selectItems
      globalData.resumeUsedJobName=this.data.selectName
    }

    if (this.data.selectItems.length>0 && this.data.selectName.length>0) {
      //提示
      wx.showToast({
        title: '保存成功',
      });

    }

    // console.log(this.data.fromUrl)
    // console.log(this.data.selectItems)
    // console.log(this.data.selectName)

    //返回上一个界面
    setTimeout(() => {
      wx.navigateBack({
        delta: 1,
      })
    }, 1000);
  }

  
})